const config = require('../config/config')
const crypto = require('crypto')

class Tool {
  static errorMsg(errArr, type) {
    if (type === 'req') {
      if (errArr.length > 0) {
        return errArr[0].msg
      }
    }
    return ''
  }

  static encrypt(data) {
    return crypto.createHash('md5').update(data).digest('hex')
  }

  static validatorError(errors) {
    return {
      code: 422,
      msg: this.errorMsg(errors.array(), 'req'),
      errors: errors.array()
    }
  }

  static exceptionError(err) {
    const uniqueConstraints = {
      login_name: '用户登录名',
      role_name: '角色名',
      mobile: '手机号码',
      email: '电子邮件地址'
    }
    if (err['name'] === 'SequelizeUniqueConstraintError') {
      const dup = Object.keys(err['fields'])[0]
      return {
        code: 500,
        msg: uniqueConstraints[dup] + '【' + err['fields'][dup] + '】已经存在'
      }
    } else {
      return {
        code: 500,
        msg: '数据库错误',
        errors: err
      }
    }
  }

  static isSysAdmin(user) {
    let isSysAdmin = false
    // 用户是超管或者是没有设置公司ID(0或者null)的管理员（isAdmin=1）被称为系统管理员，能够修改用户公司，是否管理员等权限，能够查看所有公司的数据
    if (user.id === 1 || user.isAdmin === 1) {
      isSysAdmin = true
    }
    return isSysAdmin
  }

  static isJsonString(str) {
    try {
      JSON.parse(str)
    } catch (e) {
      return false
    }
    return true
  }

  static prefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length)
  }

  static randomStr(length) {
    var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    var result = ''
    for (var i = length; i > 0; --i) {
      result += str[Math.floor(Math.random() * str.length)]
    }
    return result
  }

  static randomNum(n) {
    var rnd = ''
    for (var i = 0; i < n; i++) {
      rnd += Math.floor(Math.random() * 10)
    }
    return rnd
  }

  static getMenuName(items, val, colVal, colName) {
    for (let index = 0; index < items.length; index++) {
      const item = items[index]
      if (item[colVal] === val) {
        return item[colName]
      }
    }
    return '——'
  }

  static isFloat(n) {
    return n === +n && n !== (n | 0)
  }

  static sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  static filterDataType() {
    const ret = []
    for (let index = 0; index < config.dataTypeMap.length; index++) {
      const dataType = config.dataTypeMap[index]
      if (dataType.label !== '预留') {
        ret.push(dataType)
      }
    }
    return ret
  }

  static sortBy(attr, rev = false) {
    rev = rev ? 1 : -1
    return function(a, b) {
      a = a[attr]
      b = b[attr]
      if (a > b) {
        return rev * 1
      } else if (a < b) {
        return rev * -1
      }
      return 0
    }
  }

  static numFormat(num) {
    var result = []
    while (Math.floor(num / 1000)) {
      var temp = num % 1000
      result.push(temp)
      num = Math.floor(num / 1000)
    }
    result.push(num)
    return result.reverse().join(',')
  }

  static deepClone(obj) {
    return JSON.parse(JSON.stringify(obj))
  }
}

module.exports = Tool
